using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IShoppingBll;
using IShoppingDal;
using ShoppingEntity;

namespace ShoppingBll
{
    public class CommodityInfoBll : BaseDeleteBll<CommodityInfo>, ICommodityInfoBll
    {
        private ICommodityInfoDal _commodityInfoDal;
        private ICommodityTypeDal _commodityTypeDal;
        private IFileInfoDal _fileInfoDal;
        private IOrderInfoDal _orderInfoDal;
        private ShoppingDbContext _dbContext;
        private IUserInfoDal _userInfoDal;



        public CommodityInfoBll(IUserInfoDal userInfoDal,IOrderInfoDal orderInfoDal,ICommodityInfoDal commodityInfoDal, ICommodityTypeDal commodityTypeDal, IFileInfoDal fileInfoDal, ShoppingDbContext dbContext) : base(commodityInfoDal)
        {
            _commodityInfoDal = commodityInfoDal;
            _commodityTypeDal = commodityTypeDal;
            _fileInfoDal = fileInfoDal;
            _orderInfoDal = orderInfoDal;
            _dbContext = dbContext;
            _userInfoDal = userInfoDal;
        }

        /// <summary>
        /// 商品列表页面显示
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
        /// <param name="CommodityName"></param>
        /// <param name="CategoryId"></param>
        /// <returns></returns>
        public object GetCommodityInfoListByPage(int page, int limit, out int count, string CommodityName, string CategoryId)
        {
            //获取数据库中商品全部没删除的数据（未真实查询）
            var commodityInfos = _commodityInfoDal.GetEntitiesDb().Where(c => c.IsDelete == false);

            if (!string.IsNullOrEmpty(CommodityName))
            {
                commodityInfos = commodityInfos.Where(c => c.CommodityName.Contains(CommodityName));
            }

            if (!string.IsNullOrEmpty(CategoryId))
            {
                commodityInfos = commodityInfos.Where(c => c.CategoryId.Contains(CategoryId));
            }

            var Temp = from cm in commodityInfos
                       join ct in _commodityTypeDal.GetEntitiesDb()
                       on cm.CategoryId equals ct.ID into cctTemp
                       from cct in cctTemp.DefaultIfEmpty()
                       select new
                       {
                           cm.ID,
                           cm.CommodityName,
                           cm.Price,
                           cm.Num,
                           cm.Detail,
                           cm.CreateTime,
                           cct.CategoryName,
                           cm.CommodityImg
                       };




            //查询出来数据的数量
            count = Temp.Count();


            //分页
            Temp = Temp.OrderBy(c => c.CreateTime).Skip((page - 1) * limit).Take(limit);

            var list = Temp.ToList().Select(c => new
            {
                c.ID,
                c.CommodityName,
                c.Price,
                c.Num,
                c.Detail,
                CreateTime = c.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                CategoryId = c.CategoryName,
                c.CommodityImg
            });

            return list;
        }


        /// <summary>
        /// 获取商品名字
        /// </summary>
        /// <returns></returns>
        public object GetCommodityRecordSelectOption()
        {
            //linq
            var commodityName = _commodityInfoDal.GetEntitiesDb().Select(d => new
            {
                d.ID,
                d.CommodityName
            }).ToList();
            return commodityName;
        }

        /// <summary>
        /// 通过ID获取商品与分类
        /// </summary>
        /// <param name="commodityId"></param>
        /// <returns></returns>
        public object GetShoppingCartOption(string commodityId)
        {
            var Temp = from cm in _commodityInfoDal.GetEntitiesDb().Where(c=>c.ID==commodityId)
                       join ct in _commodityTypeDal.GetEntitiesDb()
                       on cm.CategoryId equals ct.ID into cctTemp
                       from cct in cctTemp.DefaultIfEmpty()
                       select new
                       {
                           cm.ID,
                           cm.CommodityName,
                           cct.CategoryName
                       };
            return Temp;
        }




        /// <summary>
        /// 上传商品图片
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="extensionName"></param>
        /// <param name="length"></param>
        /// <param name="iD"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool Upload(Stream stream, string extensionName, long length, string userInfoId, string oldFileName)
        {
            //获取当前程序运行的路径
            var root = Directory.GetCurrentDirectory();

            DateTime startTime = new DateTime(1970, 1, 1, 8, 0, 0);

            //时间戳
            long timeStamp = Convert.ToInt32(DateTime.Now.Subtract(startTime).TotalSeconds);
            string fileName = timeStamp + "." + extensionName;

            string filePath = Path.Combine(root, "wwwroot", "img", fileName);

            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                stream.CopyTo(fs);
            }

            return _fileInfoDal.Add(new ShoppingEntity.FileInfo()
            {
                ID = Guid.NewGuid().ToString(),
                OldFileName = oldFileName,
                NewFileName = fileName,        
                Extension = extensionName,
                Length = length,
                CreatorId = userInfoId,
                CreateTime = DateTime.Now,
            });
        }

        /// <summary>
        /// 直接在商品列表购买商品
        /// </summary>
        /// <param name="commodityId"></param>
        /// <param name="num"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool PlayCommodityOrder(string commodityId, int num, UserInfo userInfos,out string msg)
        {
            msg = "";

            UserInfo userInfo = _userInfoDal.GetEntity(userInfos.ID);

            CommodityInfo commodityInfo = _commodityInfoDal.GetEntity(commodityId);
            if (commodityInfo ==null)
            {
                msg = "商品不存在";
                return false;
            }

            if (num > commodityInfo.Num)
            {
                msg = "商品库存不足，购买失败";
                return false;
            }


            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                OrderInfo orderInfo = new OrderInfo()
                {
                    ID = Guid.NewGuid().ToString(),
                    GoodsId = commodityInfo.ID,
                    UserId = userInfo.ID,
                    Amount = commodityInfo.Price * num,
                    State = OrderInfo.OrderStateEnum.已下单,
                    Num = num,
                    OrderTime = DateTime.Now,
                    IsDelete = false
                };

                if (userInfo.Balance < commodityInfo.Price * num)
                {
                    msg = "您账户余额不足";
                    transaction.Rollback();
                    return false;
                }

                //添加到订单表中
                bool isSuccess1 = _orderInfoDal.Add(orderInfo);

                //扣除商品数量
                commodityInfo.Num = commodityInfo.Num - num;
                bool isSuccess2 = _commodityInfoDal.Update(commodityInfo);

                //扣除用户的金额
                userInfo.Balance = userInfo.Balance - commodityInfo.Price * num;
                bool isSuccess3 = _userInfoDal.Update(userInfo);

                if (isSuccess1&& isSuccess2&& isSuccess3)
                {
                    msg = "购买成功";
                    transaction.Commit();
                    return true;
                }
                else
                {
                    msg = "失败";
                    transaction.Rollback();
                    return false;
                }


            }


        }

    }
}
